<template>
  <el-row style="font-size: 14px" v-loading="reportDataLoading">
    <el-col :span="24" class="main-box">
      <div class="left-box" :style="{width:sidebar[sidebarState][0]}">
        <basic-container>
          <el-row class="search-form">
            <el-col :span="24">
              <beetles-search :size="'mini'" @search-form="getReportList" @empty-form="emptyForm" :expend="true">
                <template slot-scope="{searchConceal}" slot="searchForm">
                  <div :style="{height:searchConceal? 'auto' :'40px'}" style="overflow:hidden">
                    <el-form :model="form" inline label-width="100px">
                      <el-form-item label="时间范围:">
                        <el-date-picker
                          v-model="form.date"
                          prefix-icon="null"
                          type="daterange"
                          :clearable="false"
                          size="mini"
                          unlink-panels
                          range-separator="-"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd"
                          @change="getReportList"
                          :picker-options="pickerOptions"
                          class="select-width">
                        </el-date-picker>
                      </el-form-item>
                      <el-form-item label="媒体:">
                        <el-select
                          size="mini"
                          collapse-tags
                          clearable
                          multiple
                          v-model="form.mediaSelect"
                          @change="dimensionCheck"
                          :loading="reportDataLoading"
                          class="select-width">
                          <el-option
                            v-for="item in mediaList"
                            :key="item.value"
                            :value="item.value"
                            :label="item.label">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="广告系列名称:">
                        <el-input
                          v-model="form.adCampaignName"
                          @change="dimensionCheck"
                          clearable
                          size="mini"
                          placeholder="请输入"
                          class="select-width"/>
                      </el-form-item>
                      <el-form-item label="选择账户:">
                        <el-select
                          id="account-select"
                          clearable
                          collapse-tags
                          size="mini"
                          :loading="reportDataLoading"
                          v-model="form.accountValue"
                          filterable
                          placeholder="请选择"
                          multiple
                          @change="controlAccountId"
                          class="select-width">
                          <el-option
                            style="padding-right: 25px"
                            v-for="item in accountList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <!-- 选择多个地区 -->
                      <el-form-item label="投放地区:">
                        <el-select
                          size="mini"
                          collapse-tags
                          clearable
                          multiple
                          :loading="reportDataLoading"
                          v-model="form.geoSelect"
                          filterable
                          class="select-width">
                          <el-option
                            v-for="item in geoList"
                            :key="item.geoKey"
                            :value="item.geoKey"
                            :label="item.geoKey"
                            class="select-width">
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="广告组名称:">
                        <el-input
                          v-model="form.adSetName"
                          @change="dimensionCheck"
                          clearable
                          size="mini"
                          placeholder="请输入"
                          class="select-width"/>
                      </el-form-item>
                      <el-form-item label="广告名称:">
                        <el-input
                          v-model="form.adName"
                          @change="dimensionCheck"
                          clearable
                          size="mini"
                          placeholder="请输入"
                          class="select-width"/>
                      </el-form-item>
                      <el-form-item label="优化师:">
                        <el-select
                          clearable
                          size="mini"
                          :loading="reportDataLoading"
                          v-model="form.operatorValue"
                          filterable
                          placeholder="请选择"
                          multiple
                          @change="getReportList"
                          class="select-width">
                          <el-option
                            style="padding-right: 25px"
                            v-for="item in operatorList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-form>
                  </div>
                </template>
              </beetles-search>
            </el-col>
          </el-row>
          <el-row v-if="tableActiveName === 'report'">
            <div style="float: right;">
              <span style="line-height: 28px;">
                选择模板:
              </span>
              <el-select v-model="templateSelect" placeholder="请选择" style="width: 125px; margin-right: 5px"
                         size="mini"
                         @change="templateChange">
                <el-option
                  v-for="item in templateList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    <el-button size="mini" @click="deleteTemplate(item.id, item.name)" type="text"><i
                      class="el-icon-delete"/></el-button>
                  </span>
                </el-option>
              </el-select>
              <el-button type="primary" size="mini" style="width: 60px; padding: 6px" @click="handleModelOpen">保存模板
              </el-button>
            </div>
          </el-row>
          <div style="display: flex;justify-content: space-between;margin-top: 1em">
            <div v-if="tableActiveName === 'report'">
              <el-button type="primary" size="mini" style="margin-right: 8px" @click="clearChecked">清空已选指标</el-button>
              <span>合并单元格: </span>
              <el-switch
                v-model="spanFlag"
                :disabled="reportDataLoading"
                @change="getReportList"
              />
            </div>
            <div>
            <span v-if="tableActiveName === 'report' && exportBtn">
              <el-button @click="exportData" type="primary" size="mini" :loading="exportLoading">导出报表</el-button>
              <a id="exportInOcIndexLink"/>
            </span>
            </div>
          </div>
          <el-row>
            <div style="margin-top: 7px;color: #00a680">温馨提示：走账订单一周更新一次数据</div>
          </el-row>

          <!--<el-tabs v-model="tableActiveName" @tab-click="handleCheck(true)">
            <el-tab-pane label="报 表" name="report">-->
          <el-table
            class="report-table"
            ref="reportTable"
            border
            :data="reportData"
            :span-method="spanMethod"
            :header-cell-style="headerStyle"
            :show-summary="reportData.length > 1"
            :summary-method="getSummaries"
            @sort-change="handleSort"
            max-height="770px"
            style="width: 100%;">
            <el-table-column
              v-for="item in columnList" :key="item.value"
              :fixed="activeList[0] === item.value && reportData.length > 1"
              :prop="item.value"
              :label="item.label"
              :align="'center'"
              sortable="custom"
              v-if="activeList.indexOf(item.value) !== -1">

              <template
                slot="header"
                slot-scope="scope"
              >
                <span>{{ scope.column.label }}
                  <span v-show="scope.column.label === '安装数'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span>TikTok暂不支持iOS14分国家数据</span>
                      </div>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                  <span v-show="scope.column.label === '媒体'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span>tiktok展示为前天数据</span>
                      </div>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                  <span v-show="scope.column.label === '投放地区'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span>广告/素材实际产生归因数据的国家/地区</span>
                      </div>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                  <span v-show="scope.column.label === '操作系统'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <span>在广告后台配置的目标操作系统</span>
                      </div>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                  <span v-show="scope.column.label === '安装成本'">
                    <el-tooltip placement="top">
                      <div slot="content">
                        <div><p>Facebook - install 安装</p>
                          <p>Bigo Ads - install 去重安装</p>
                          <p>Google Ads - installation 安装</p>
                          <p>Tiktok - conversions 转化数</p>
                        </div>
                      </div>
                      <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                </span>
              </template>


            </el-table-column>
          </el-table>
          <!--</el-tab-pane>
          <el-tab-pane label="趋势图" name="chart">
            <div
              v-for="(item, index) in basicAndEventList" :key="index" class="chart-container"
              v-show="activeList.indexOf(item.value) !== -1">
              <div
                :id="item.value"
                :title="item.label"
                :ref="item.value"
                style="height: 400px; width: 100%"
              />
            </div>
          </el-tab-pane>
        </el-tabs>-->
          <span style="font-weight: bold; position: absolute; bottom: -18px" v-if="tableActiveName === 'report'">
              {{
              (reportDataLoading && reportData.length === 0) ? '加载中。。。' : '已加载：' + reportData.length + ' / ' + query.total
            }}
          </span>
        </basic-container>
        <div class="sidebar-toggle">
          <div class="sidebar-toggle-icon" @click="changeSide">
            <i :class="sidebar[sidebarState][2]"></i>
          </div>
        </div>
      </div>
      <div class="right-box" :style="{width:sidebar[sidebarState][1]}">
        <basic-container><!-- style="position: fixed; width: 15%"-->
          <el-scrollbar><!-- style="min-height: 756px"-->
            <el-tabs v-model="dimensionActiveName">
              <el-tab-pane label="广告维度" name="dimension" style="max-height: 800px; overflow-y: auto">
                <el-tree
                  ref="dimensionRef"
                  :data="dimensionTree"
                  :props="{ label: 'label'}"
                  :default-checked-keys="activeList"
                  default-expand-all
                  show-checkbox
                  node-key="value"
                  check-on-click-node/>
              </el-tab-pane>
              <el-tab-pane label="数据指标" name="index" style="min-height: 400px; max-height: 800px; overflow-y: auto">
                <div style="overflow-x: scroll; width: 200px">
                  <el-tree
                    ref="basicRef"
                    :indent="8"
                    check-strictly
                    default-expand-all
                    :data="basicTree"
                    :props="{ label: 'label', children: 'children' }"
                    :default-checked-keys="activeList"
                    show-checkbox
                    node-key="value"
                    check-on-click-node/>

                  <el-tree
                    ref="eventRef"
                    empty-text='如无三方数据,请检查"App管理-跟踪配置"是否正确配置'
                    :indent="8"
                    style="margin-top: 15px"
                    check-strictly
                    default-expand-all
                    :data="eventTree"
                    :props="{ label: 'label', children: 'children' }"
                    :default-checked-keys="activeList"
                    show-checkbox
                    node-key="value"
                    check-on-click-node>
                    <template v-slot="{ node }">
                      <el-tooltip v-if="showTreeTip.includes(node.label)" effect="dark"
                                  :content="node.label| getTreeTip" placement="right">
                        <span>{{ node.label }}</span>
                      </el-tooltip>
                      <span v-else>{{ node.label }}</span>
                    </template>
                  </el-tree>

                  <el-tree
                    ref="platformEventRef"
                    empty-text='媒体事件'
                    :indent="8"
                    style="margin-top: 15px"
                    check-strictly
                    default-expand-all
                    :data="platformEventTree"
                    :props="{ children: 'children',
                label(data) {
                  return data.label || data.platform
                } }"
                    show-checkbox
                    node-key="value"
                    check-on-click-node>
                  </el-tree>
                </div>
              </el-tab-pane>
            </el-tabs>
            <el-button type="primary" @click="dimensionCheck" style="margin-top: 30px;margin-left: 40px;">生成报表
            </el-button>
          </el-scrollbar>
        </basic-container>
      </div>
    </el-col>
    <el-dialog :visible.sync="saveDialog" append-to-body width="30%"
               :close-on-click-modal="false" :show-close="false">
      <div>
        <el-form ref="modelFormRef" :model="modelForm" :rules="modelRules"
                 style="margin: 0 auto;width: 80%;text-align: center">
          <el-form-item prop="modelFormat">
            <el-radio-group v-model="modelForm.modelFormat">
              <el-radio label="0" @change="setTemplateName(true)" :disabled="templateSelect && !isNaN(templateSelect)">
                保存为新模板
              </el-radio>
              <el-radio label="1" @change="setTemplateName(false)" :disabled="templateList.length === 0">覆盖当前的模板
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="modelName" label="模板名：" style="position: relative">
            <el-input size="mini" placeholder="请输入模板名称" v-model="modelForm.modelName"/>
            <span v-if="modelForm.modelFormat === '1'"
                  style="color: #f56c6c; position: absolute; left: 0; top: 86px; width: 200px; text-align: left; font-size: 12px">您可以对现有模板重命名</span>
          </el-form-item>
          <el-form-item style="margin-top: 45px">
            <el-button type="primary" size="mini" @click="saveModel">确定</el-button>
            <el-button size="mini" @click="saveDialog = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
import store from "@/store/";
import {getOfferAccount, getOfferOperator} from "@/api/business/account";
import {createEventHandler} from "@/util/events";
import {
  deleteTemplate,
  getDimensionByGroup,
  getReport,
  getTemplateList,
  saveTemplate,
  updateTemplate,
  getReportTotal,
  exportReport,
  getEventByOfferId,
  updateUseTime, getPlatformEventByOfferId
} from "@/api/dataReport/offerReport";
import {getGeoList} from "@/api/system/dict";
import {getOfferName} from "@/api/business/offer"
import Moment from 'moment';
import * as echarts from "echarts";
import {mapGetters} from "vuex";
import {transformObjectList, findObject} from "@/util/util";
import {getSysDictList} from "@/api/system/dict";
import beetlesSearch from "@/components/basic-components/beetles-search"

export default {
  name: "dataReport",
  components: {
    beetlesSearch
  },
  data() {
    return {
      pickerOptions: {
        // disabledDate(time) {
        //   return time.getTime()>Moment(new Date()).subtract(1,'days')
        // },
        shortcuts: [{
          text: '昨日',
          onClick(picker) {
            const start = Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD')
            picker.$emit('pick', [start, start])
          }
        }, {
          text: '当周',
          onClick(picker) {
            const weekOfDay = Moment().format('E')
            const start = Moment().subtract(weekOfDay - 1, 'days').format('YYYY-MM-DD')
            const end = Moment().add(7 - weekOfDay, 'days').format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          },
        }, {
          text: '上周',
          onClick(picker) {
            const weekOfday = parseInt(Moment().format('E'))
            const start = Moment().subtract(weekOfday - 1 + 7, 'days').format('YYYY-MM-DD')
            const end = Moment(new Date()).subtract(weekOfday, 'days').format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '当月',
          onClick(picker) {
            const end = Moment(new Date()).subtract(-1).format('YYYY-MM-DD')
            const start = Moment().startOf('months').format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '上月',
          onClick(picker) {
            const start = Moment().subtract('month', 1).format('YYYY-MM') + '-01'
            const end = Moment(start).subtract('month', -1).add('days', -1).format('YYYY-MM-DD')
            picker.$emit('pick', [start, end])
          }
        }]
      },
      form: {
        date: [],
        accountValue: [],
        geoSelect: [],
        mediaSelect: [],
        adCampaignName: null,
        adSetName: null,
        adName: null,
        operatorValue: []
      },
      offerId: store.state.user.offer,
      userName: store.state.user.userInfo.nick_name,
      accountList: [],
      operatorList: [],
      activeList: ['report_date', 'spend', 'impressions', 'clicks', 'cpm', 'install', 'cpa'],  // 默认指标
      dimensionActiveName: 'dimension',
      tableActiveName: 'report',//列表标签
      saveDialog: false, //保存弹窗
      modelForm: {
        modelFormat: '0',
        modelName: '',
      },
      dimensionTree: [],
      basicTree: [],
      eventTree: [],
      dimensionData: [],
      basicData: [],
      eventData: [],
      modelRules: {
        modelFormat: [{required: true, message: '请选择模板保存形式', trigger: 'change'}],
        modelName: [{required: true, message: '请输入模板名称', trigger: 'blur'}]
      },
      templateList: [],
      templateSelect: '',
      templateSelectOld: '',
      templateDefaultName: '',
      columnList: [],
      basicAndEventList: [],
      reportData: [],
      reportDataLoading: false,
      spanData: [],
      spanFlag: true,
      trendChartList: [],
      query: {
        current: 1,
        size: 80,
        total: 0,
        pages: null,
        sortBy: null,
        isAsc: true
      },
      reportTotal: [],
      exportLoading: false,
      exportBtn: false,
      geoList: [],
      mediaList: [],
      // marco
      // 媒体事件
      platformEventTree: [],
      platformEventData: [],
      sidebar: {
        open: ['80%', '20%', 'el-icon-arrow-right'],
        closed: ['100%', '0%', 'el-icon-arrow-left']
      },
      sidebarState: 'open',
      showTreeTip: ['总数', '独立用户', '总价值', '费用', '价值', '转化率']
    }
  },
  computed: {
    ...mapGetters(["permission"])
  },
  /*watch: {
    dimensionData() {
      this.activeList = []
      this.activeList.push(...this.dimensionData, ...this.basicData, ...this.eventData)
    }
  },*/
  filters: {
    getTreeTip(originVar) {
      switch (originVar) {
        case '总数':
          return '事件触发的次数'
        case '独立用户':
          return '触发事件的独立用户人数'
        case '总价值':
          return '每次事件触发带来的价值之和'
        case '费用':
          return '单次事件触发的消耗成本，媒体花费/事件总数'
        case '价值':
          return '单次事件触发产生的价值，总价值/事件总次数'
        case '转化率':
          return '事件次数/安装数'
        default:
          return ''
      }
    }
  },
  beforeRouteLeave(to, form, next) {
    let self = this
    if (self.eventHandler) {
      self.eventHandler.clear()
    }
    next()
  },
  created() {
    if(this.$route.query.platformId !== undefined) {
      this.form.accountValue = [this.$route.query.platformId]
    }
    getSysDictList('platforms').then(map => {
      this.mediaList = transformObjectList(map['platforms'], [
        {from: 'dictKey', to: 'value'},
        {from: 'dictValue', to: 'label'},
      ]);
    });
    // 设置默认模板名
    this.templateDefaultName = '自定义-' + this.userName + '-' + Moment(new Date()).format('YYYY-MM-DD')
    // 设置默认时间
    this.form.date = [Moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'),
      Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD')]
    let self = this
    this.eventHandler = createEventHandler("offerCenter")
      .addListener((event) => {
        if (event.message === 'offerChanged' && event.offerId && event.offerId !== "") {
          self.offerId = store.state.user.offer
          self.accountList = []
          self.operatorList = []
          self.form.accountValue = []
          self.form.operatorValue = []
          self.columnList = []
          self.reportData = []
          self.getOfferAccount()
          self.getOfferOperator()
          self.getDimensionByGroup()
          //self.getTemplateList()
        }
      });
  },
  mounted() {
    this.exportBtn = this.permission.data_report_oc_export

    this.getOfferAccount()
    this.getOfferOperator()
    this.getDimensionByGroup()
    this.getGeo()
    //this.getTemplateList()

    //let table = this.$refs.reportTable
    this.$refs.reportTable.bodyWrapper.addEventListener("scroll", (res) => {
      const height = res.target
      const scrollDistance = height.scrollHeight - height.scrollTop - height.clientHeight;
      if (height.scrollTop > 0 && scrollDistance === 0) {  // 等于0证明已经到底，可以请求接口
        if (this.query.current < this.query.pages) {  // 当前页数小于总页数就请求
          this.query.current++
          this.getReport()
        }
      }
    })
  },
  methods: {
    // 趋势图
    initTrendLine(element) {
      element.style.width = window.innerWidth * 0.58 + 'px'
      let myChart = echarts.init(element)
      let option
      option = {
        title: {
          text: element.title
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['花费', '安装数']
        },
        toolbox: {
          feature: {
            //saveAsImage: { show: true }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            name: '花费',
            type: 'line',
            stack: 'Total',
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: '安装数',
            type: 'line',
            stack: 'Total',
            data: [220, 182, 191, 234, 290, 330, 310]
          },
        ]
      }
      option && myChart.setOption(option);
      myChart.resize()
    },
    controlAccountId(val) {
      if (val.findIndex(item => item === "") !== -1 && val.length > 1 && val[val.length - 1] !== "") {
        val.splice(val.findIndex(item => item === ""), 1)
      } else if (val.length === 0 || val[val.length - 1] === "") {
        val = []
      }
      this.form.accountValue = val
      this.getReportList()
    },
    getOfferAccount() {
      getOfferAccount(this.offerId).then(res => {
        this.accountList = res.data.data
        //this.accountList = [{value: '', label: '全部'}, ...res.data.data]
      })
    },
    getOfferOperator() {
      getOfferOperator(this.offerId).then(res => {
        this.operatorList = res.data.data
      })
    },
    getDimensionByGroup() {
      getDimensionByGroup(1).then(res => {
        this.dimensionTree = res.data.data
        this.columnList.push(...res.data.data)
      }).then(() => {
        getDimensionByGroup(2).then(res => {
          this.basicTree = []
          this.basicTree.push({'label': '媒体数据', 'children': res.data.data, 'disabled': true})
          this.columnList.push(...res.data.data)
          this.basicAndEventList.push(...res.data.data)
        }).then(async () => {
          this.eventTree = []
          const res = await getEventByOfferId(this.offerId)
          let response = res.data.data
          if (response.length > 0) {
            response.forEach(event => {
              event.disabled = true
              event.children.forEach(item => {
                this.columnList.push({'label': event.label + ' ' + item.label, 'value': item.value})
                this.basicAndEventList.push({'label': event.label + item.label, 'value': item.value})
              })
            })
            this.eventTree.push({'label': '三方数据', 'children': response, 'disabled': true})
          }
          await this.getPlatformEventTree()
          this.getTemplateList()
        })
      })
    },
    getTemplateList() {
      this.templateSelect = null
      getTemplateList(this.offerId).then(res => {
        this.templateList = res.data.data.list
        // console.log('模板', this.templateList)
        for (let i = 0; i < this.templateList.length; i++) {
          if (this.templateList[i].id === res.data.data.select) {
            this.templateSelect = this.templateList[i].id
            this.templateChange(this.templateList[i].id)
            return
          }
        }
        this.$refs.dimensionRef.setCheckedKeys(["report_date"])
        this.$refs.basicRef.setCheckedKeys(["spend", "impressions", "clicks", "ctr", "cpm", "install", "cpa", "cvr"])
        this.getReportList()
      })
    },
    dimensionCheck() {
      this.templateSelect = '【自定义模板】'
      this.getReportList()
    },
    getReportList() {
      this.reportData = []
      this.query.current = 1
      this.assignCheck()
      if (this.activeList.indexOf(this.query.sortBy) === -1) {
        this.query.sortBy = null
      }
      this.getReport()
    },
    getReport() {
      if (this.tableActiveName === 'report') {
        this.reportDataLoading = true
        this.spanData = []
        let data = {
          'startDate': this.form.date[0],
          'endDate': this.form.date[1],
          'accountIds': this.form.accountValue[0] === '' ? null : this.form.accountValue,
          'operatorIds': this.form.operatorValue[0] === '' ? null : this.form.operatorValue,
          'geoSelect': this.form.geoSelect,
          'adCampaignName': this.form.adCampaignName==null ? '':this.form.adCampaignName.trim(),
          'adSetName': this.form.adSetName==null ? '':this.form.adSetName.trim(),
          'adName': this.form.adName==null ? '':this.form.adName.trim(),
          'mediaSelect': this.form.mediaSelect,
          'dimensions': this.dimensionData,
          'basicData': this.basicData,
          'eventData': this.eventData,
          'offerId': this.offerId,
          'size': this.query.size,
          'current': this.query.current,
          'sortBy': this.query.sortBy,
          'isAsc': this.query.isAsc,
          // 媒体事件
          "platformEvent": this.platformEventData
        }
        getReport(data).then(res => {
          this.reportData.push(...res.data.data.records)
          this.query.total = res.data.data.total
          this.query.pages = res.data.data.pages
          this.reportDataLoading = false
          this.spanControl(this.reportData)
        }).then(() => {
          if (this.query.current === 1 && this.reportData.length > 1) {
            getReportTotal(data).then((res) => {
              this.reportTotal = res.data.data
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '接口繁忙，请稍后重试！'
          })
          this.reportDataLoading = false
        })

      } else {

        //this.trendChartList = this.trendChartList ?
        this.basicData.forEach(item => {
          let element = document.getElementById(item)
          this.initTrendLine(element)
        })
        this.eventData.forEach(item => {
          let element = document.getElementById(item)
          this.initTrendLine(element)
        })
        // 媒体事件
        this.platformEventData.forEach(item => {
          let element = document.getElementById(item)
          this.initTrendLine(element)
        })
      }
    },
    assignCheck() {
      this.dimensionData = this.$refs.dimensionRef.getCheckedKeys()
      this.basicData = this.$refs.basicRef.getCheckedKeys()
      this.eventData = this.$refs.eventRef.getCheckedKeys()
      // 媒体事件
      this.platformEventData = this.$refs.platformEventRef.getCheckedKeys()
      // console.log('platform',this.platformEventData)
      // console.log('event',this.eventData)
      this.activeList = []
      this.activeList.push(...this.dimensionData, ...this.basicData, ...this.eventData, ...this.platformEventData)
    },
    clearChecked() {
      this.$refs.dimensionRef.setCheckedKeys([])
      this.$refs.basicRef.setCheckedKeys([])
      this.$refs.eventRef.setCheckedKeys([])
      this.$refs.platformEventRef.setCheckedKeys([])

      this.activeList = []
      this.reportData = []
      this.query.total = 0
      this.query.pages = 0
      this.templateSelect = '【自定义模板】'
    },
    /**
     * 保存模板
     */
    saveModel() {
      this.$refs.modelFormRef.validate(valid => {
        if (valid) {
          this.assignCheck()
          let data = {
            'id': this.templateSelectOld,
            'name': this.modelForm.modelName,
            'dimensions': this.dimensionData.join(","),
            'basicData': this.basicData.join(","),
            'eventData': this.eventData.join(","),
            'geoSelect': this.form.geoSelect.join(","),
            'mediaSelect': this.form.mediaSelect.join(","),
            'adCampaignName': this.form.adCampaignName,
            'adSetName': this.form.adSetName,
            'offerId': this.offerId,
            "platformEvent": this.platformEventData.join(",")
          }
          if (this.modelForm.modelFormat === '0') {
            let id = this.findTemplateByName(data.name)
            if (id) {
              this.$confirm('此模板名已经存在，是否要覆盖该模板？', '提示', {
                confirmButtonText: '覆盖',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                data.id = id
                this.updateTemplate(data)
              })
            } else {
              this.saveTemplate(data)
            }
          } else if (this.modelForm.modelFormat === '1' && data.id) {
            this.updateTemplate(data)
          } else {
            this.$message({
              type: "error",
              message: "当前未选择覆盖模板！"
            })
          }
        }
      })
    },
    /**
     * 关闭模板弹窗
     */
    handleModelClose() {
      this.saveDialog = false
      this.getTemplateList()
    },
    handleModelOpen() {
      this.saveDialog = true
      if (this.templateSelect && !isNaN(this.templateSelect)) {
        this.modelForm.modelFormat = '1'
        this.setTemplateName(false)
      } else {
        this.modelForm.modelFormat = '0'
        this.setTemplateName(true)
      }
    },
    findTemplateByName(name) {
      for (let i = 0; i < this.templateList.length; i++) {
        if (this.templateList[i].name === name) {
          return this.templateList[i].id
        }
      }
      return false
    },
    saveTemplate(data) {
      saveTemplate(data).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        })
        this.handleModelClose()
      })
    },
    updateTemplate(data) {
      updateTemplate(data).then(() => {
        this.$message({
          type: "success",
          message: "操作成功!"
        })
        this.handleModelClose()
      })
    },
    // 更换模板
    templateChange(val) {
      this.templateList.map(item => {
        if (item.id === val) {
          this.modelForm.modelFormat = '0'
          this.modelForm.modelName = this.templateDefaultName
          this.templateSelectOld = item.id
          this.$refs.dimensionRef.setCheckedKeys(item.dimensions.split(','))
          this.$refs.basicRef.setCheckedKeys(item.basicData.split(','))
          this.$refs.eventRef.setCheckedKeys(item.eventData.split(','))
          this.$refs.platformEventRef.setCheckedKeys(item.platformEvent.split(','))
          this.form.geoSelect = item.geoSelect ? item.geoSelect.split(',') : []
          this.form.mediaSelect = item.mediaSelect ? item.mediaSelect.split(',') : []
          this.form.adCampaignName = item.adCampaignName
          this.form.adSetName = item.adSetName
          this.getReportList()
          updateUseTime(item.id)
        }
      })
    },
    setTemplateName(flag) {
      if (flag) {
        this.modelForm.modelName = this.templateDefaultName
      } else {
        this.templateList.map(item => {
          if (item.id === this.templateSelectOld) {
            this.modelForm.modelName = item.name
          }
        })
      }
    },
    deleteTemplate(id, name) {
      this.$confirm("确定删除模板【" + name + "】?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteTemplate(id).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          })
          this.getTemplateList()
          this.templateSelect = null
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    spanMethod({rowIndex, columnIndex}) {
      if (this.spanFlag && columnIndex < this.dimensionData.length) {
        let data = this.spanData
        for (let i = 0; i < data.length; i++) {
          if (data[i].columnIndex === columnIndex && data[i].rowIndex === rowIndex) {
            return {
              rowspan: data[i].rowspan,
              colspan: data[i].colspan
            }
          }
        }
      }
    },
    spanControl(data) {
      let temp, count, obj
      let dimensions = this.dimensionData
      if (data.length > 0) {
        for (let i = 0; i < dimensions.length; i++) {
          count = 1
          temp = data[0][dimensions[i]]
          for (let j = 1; j < data.length; j++) {
            if (temp === data[j][dimensions[i]] && (i === 0 || this.spanValid((j - 1), i))) {
              count++
              obj = {
                'columnIndex': i,
                'rowIndex': j,
                'rowspan': 0,
                'colspan': 0
              }
              this.spanData.push(obj)
              if (j === data.length - 1) {
                obj = {
                  'columnIndex': i,
                  'rowIndex': j - count + 1,
                  'rowspan': count,
                  'colspan': 1
                }
                this.spanData.push(obj)
              }
            } else {
              temp = data[j][dimensions[i]]
              if (count > 1) {
                obj = {
                  'columnIndex': i,
                  'rowIndex': j - count,
                  'rowspan': count,
                  'colspan': 1
                }
                count = 1
                this.spanData.push(obj)
              }
            }
          }
        }
      }
    },
    spanValid(rowIndex, columnIndex) {
      let valid = false
      this.spanData.forEach(item => {
        if (item.columnIndex === columnIndex - 1 && (rowIndex >= item.rowIndex && rowIndex < (item.rowIndex + item.rowspan - 1))) {
          valid = true
        }
      })
      return valid
    },
    headerStyle({row, columnIndex}) {
      if (this.dimensionData.indexOf(row[columnIndex].property) !== -1)
        return {
          "font-size": "15px",
          "font-weight": "bold",
          "background-color": "#eee7e7",
          "color": "black"
        }
      else if (this.basicData.indexOf(row[columnIndex].property) !== -1)
        return {
          "font-size": "15px",
          "font-weight": "bold",
          "background-color": "#f7f7f0",
          "color": "black"
        }
      else if (this.eventData.indexOf(row[columnIndex].property !== -1))
        return {
          "font-size": "15px",
          "font-weight": "bold",
          "background-color": "#f0f8f8",
          "color": "black"
        }
    },
    getSummaries({columns}) {
      let sums = []

      for (let index = 0; index < columns.length; index++) {
        let column = columns[index]
        if (index === 0) {
          sums[index] = '合计：'
        } else if (this.dimensionData.indexOf(column.property) !== -1) {
          sums[index] = '-'
        } else {
          sums[index] = this.reportTotal[column.property]
        }
      }

      return sums;
    },
    handleSort({prop, order}) {
      if (order !== null) {
        this.query.sortBy = prop
        this.query.isAsc = order === 'ascending'
      } else {
        this.query.sortBy = null
      }
      this.getReportList()
    },
    exportExcelBackend() {
      if (this.reportData.length === 0) {
        this.$message({
          type: 'error',
          message: '当前表格无数据'
        })
      } else {
        this.exportLoading = true
        this.assignCheck()
        let data = {
          'startDate': this.form.date[0],
          'endDate': this.form.date[1],
          'accountIds': this.form.accountValue[0] === '' ? null : this.form.accountValue,
          'operatorIds': this.form.operatorValue ? null : this.form.operatorValue,
          'geoSelect': this.form.geoSelect,
          'mediaSelect': this.form.mediaSelect,
          'adCampaignName': this.form.adCampaignName,
          'adSetName': this.form.adSetName,
          'dimensions': this.dimensionData,
          'basicData': this.basicData,
          'eventData': this.eventData,
          'offerId': this.offerId,
          'sortBy': this.query.sortBy,
          'isAsc': this.query.isAsc,
          "platformEvent": this.platformEventData
        }
        exportReport(data).then(res => {
          let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
          let url = window.URL.createObjectURL(new Blob([res.data]))
          let link = document.createElement("a")
          link.style.display = "none"
          link.href = url
          link.download = filename
          document.body.appendChild(link)
          link.click()
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '接口繁忙，请稍后重试！'
          })
          this.reportDataLoading = false
        }).finally(() => {
          this.exportLoading = false
        })
      }
    },
    generateColumnStyle(style) {
      if (style == null || style == '') {
        return '';
      } else {
        return 'style="' + style + '"';
      }
    },
    generateTable(title, headers, rowList, bottom) {
      let columnCount = 1;
      if (headers != null && headers.length > 0) {
        columnCount = headers.length;
      } else if (rowList != null && rowList.length > 0) {
        columnCount = rowList[0].length;
      }
      let resultList = [];
      resultList.push('<table border="1">');
      /*if(title != null && title.data != null && title.data != '') {
        resultList.push('<tr>');
        resultList.push('<td ' + this.generateColumnStyle(title.style) + ' colspan="' + columnCount + '">' + title.data + '</td>');
        resultList.push('</tr>');
      }*/
      if (headers != null && headers.length > 0) {
        resultList.push('<tr>');
        headers.forEach((header) => {
          resultList.push('<td ' + this.generateColumnStyle(header.style) + '>' + header.data + '</td>');
        });
        resultList.push('</tr>');
      }
      if (rowList != null && rowList.length > 0) {
        rowList.forEach((row) => {
          resultList.push('<tr>');
          if (row == null || row.length == 0) {
            resultList.push('<td colspan="' + columnCount + '"></td>');
          } else if (row.length == 1) {
            resultList.push('<td ' + this.generateColumnStyle(row[0].style) + ' colspan="' + columnCount + '">' + row[0].data + '</td>');
          } else {
            row.forEach((item) => {
              resultList.push('<td ' + this.generateColumnStyle(item.style) + ((item.colspan == null || item.colspan < 1) ? '' : ' colspan="' + item.colspan + '"') + '>' + item.data + '</td>');
            });
          }
          resultList.push('</tr>');
        });
      }
      if (bottom != null && bottom.length == 2) {
        resultList.push('<tr>');
        resultList.push('<td>' + bottom[0].data + '</td>');
        resultList.push('<td colspan="' + (columnCount - 1) + '">' + bottom[1].data + '</td>');
        resultList.push('</tr>');
      }
      resultList.push('</table>');
      return resultList.join("");
    },
    generateTableData(totalReportData) {
      let tableData = {
        title: null,
        headers: [],
        rowList: [],
        bottom: [],
      };
      let idDataStyle = 'vnd.ms-excel.numberformat:@';
      let idName = ["platform_id", "campaign_id", "adset_id", "ad_id"]
      //let totalReportData = this.reportData;
      tableData.title = {data: 'OC-订单报表导出', style: 'text-align: left; background-color: lightblue;'};
      this.columnList.forEach((item) => {
        if (this.activeList.indexOf(item.value) !== -1) {
          tableData.headers.push({data: item.label, style: 'text-align: right; background-color: #409eff;'});
        }
      });
      let style = 'text-align: right;';
      for (let rowIdx = 0; rowIdx < totalReportData.length; rowIdx++) {
        let row = [];
        this.columnList.forEach((item) => {
          if (this.activeList.indexOf(item.value) !== -1) {
            if (idName.indexOf(item.value) !== -1) {
              row.push({data: totalReportData[rowIdx][item.value], style: style + idDataStyle});
            } else {
              row.push({data: totalReportData[rowIdx][item.value], style: style});
            }
          }
        });
        tableData.rowList.push(row);
      }
      if (totalReportData.length >= 2) {
        let self = this;
        let row = [];
        this.columnList.forEach((item) => {
          if (self.activeList.indexOf(item.value) !== -1) {
            if (row.length == 0) {
              row.push({data: '合计', style: 'text-align: left; background-color: lightblue;'});
            } else if (this.dimensionData.indexOf(item.value) !== -1) {
              row.push({data: '-', style: 'text-align: right; background-color: lightblue;'});
            } else {
              row.push({data: self.reportTotal[item.value], style: 'text-align: right; background-color: lightblue;'});
            }
          }
        });
        tableData.rowList.push(row);
      }

      return tableData;
    },
    exportData() {
      if (this.reportData.length === 0) {
        this.$message({
          type: 'error',
          message: '当前表格无数据'
        })
      } else {
        this.exportLoading = true
        let data = {
          'startDate': this.form.date[0],
          'endDate': this.form.date[1],
          'accountIds': this.form.accountValue[0] === '' ? null : this.form.accountValue,
          'operatorIds': this.form.operatorValue ? null : this.form.operatorValue,
          'geoSelect': this.form.geoSelect,
          'mediaSelect': this.form.mediaSelect,
          'adCampaignName': this.form.adCampaignName,
          'adSetName': this.form.adSetName,
          'dimensions': this.dimensionData,
          'basicData': this.basicData,
          'eventData': this.eventData,
          'offerId': this.offerId,
          'size': 1,
          'current': 1,
          'sortBy': this.query.sortBy,
          'isAsc': this.query.isAsc,
          'total': true,
          'isGeoTranslate': "true",
          "platformEvent": this.platformEventData
        }
        getReport(data).then(res => {
          let tableData = this.generateTableData(res.data.data.records);
          // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
          let html = "<html><head><meta charset='utf-8' /></head><body>" + this.generateTable(tableData.title, tableData.headers, tableData.rowList, tableData.bottom) + "</body></html>";
          // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
          let blob = new Blob([html], {type: "application/vnd.ms-excel"});
          let a = document.getElementById("exportInOcIndexLink");
          // 利用URL.createObjectURL()方法为a元素生成blob URL
          a.href = URL.createObjectURL(blob);
          // 设置文件名
          getOfferName(this.offerId).then(res => {
            let filename = res.data.data + '_' + this.form.date[0] + '-to-' + this.form.date[1] + '_' + Moment(this.refreshDate).format('YYYY-MM-DD') + '-export'
            a.download = filename + '.xls';
            a.click();
          })

        }).finally(() => {
          this.exportLoading = false
        })
      }
    },
    getGeo() {
      getGeoList().then(res => {
        this.geoList = res.data.data
      })
    },
    // 获取媒体事件树状结构
    async getPlatformEventTree() {
      this.platformEventTree = []
      const {data: res} = await getPlatformEventByOfferId(this.offerId)
      let response = res.data
      if (response.length > 0) {
        response.forEach(event => {
          event.disabled = true
          event.children.forEach(platform => {
            platform.children.forEach(children => {
                this.columnList.push({'label': children.name, 'value': children.value})
                this.basicAndEventList.push({'label': children.name, 'value': children.value})
              }
            )
          })
        })
        this.platformEventTree.push({'label': '媒体事件', 'children': response, 'disabled': true})
      }
      console.log('媒体事件columnList', this.basicAndEventList)
      console.log('媒体事件basicAndEventList', this.basicAndEventList)
    },
    emptyForm() {
      this.form = {
        date: [Moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD'),
          Moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD')],
        accountValue: [],
        geoSelect: [],
        mediaSelect: [],
        adCampaignName: null,
        adSetName: null,
        operatorValue: []
      }
      this.getReportList()
    },
    changeSide() {
      this.sidebarState = this.sidebarState === 'open' ? 'closed' : 'open'
    },
    test(node) {
      console.log(node)
      return 'aaa'
    }
  }
}
</script>

<style lang="scss" scoped>
.search-form {
  /deep/ .el-form-item {
    margin-bottom: 0;
  }
}

/deep/ .el-tree {
  padding-top: 15px;
  padding-left: 10px;

  .el-tree-node {
    .is-leaf + .el-checkbox .el-checkbox__inner {
      display: inline-block;
    }

    .el-checkbox .el-checkbox__inner {
      display: none;
    }
  }
}

.chart-container {
  width: 85%;
  margin: 20px auto 50px;
  box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  border-radius: 20px;
  padding: 8px;
}

.search-label {
  width: 35%;
  display: inline-block
}

.search-item {
  width: 62%;
  display: inline-block
}

/deep/ .el-select__tags-text {
  display: inline-block;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/deep/ .el-select .el-tag__close.el-icon-close {
  top: -7px;
}

.select-width {
  width: 200px;
}

/deep/ .el-date-editor .el-range-input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  border: none;
  outline: 0;
  padding: 0;
  width: 100%;
  color: #606266;
}

.report-table {
  margin-top: 15px;
}

.main-box {
  display: flex;

  .left-box {
    position: relative;
    transition: all 0.3s ease;

    .sidebar-toggle {
      position: absolute;
      top: 50%;
      right: -5px;
      bottom: 0;
      width: 10px;
      height: 35px;
      cursor: pointer;
      background: #79cdfb;
      border-radius: 6px;
      //line-height: 35px;
      //text-align: center;
      color: #FFFFFF;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .right-box {
    transition: all 0.3s ease;
  }
}
</style>
